<template>
  <div>
    <SubTitle title="家庭成员情况" mt="60px" />
    <div class="family-list-container" v-loading="loadingMem">
      <div v-if="familyMembers.length === 0" class="null-area">
        成员关系还未绑定，前往
        <span @click="detailDialog = true">绑定</span>
      </div>
      <div class="family-list-item" v-for="mem in familyMembers">
        <div class="lst-header">
          <div class="lst-uname">
            {{ mem.uname }}
          </div>
          <div class="lst-identy">
            <span>{{ mem.identity }}</span>
          </div>
          <div class="lst-options">
            <el-button
              @click="unTieRelation(mem.uid)"
              type="warning"
              size="small"
              plain
            >解绑关系</el-button>
          </div>
        </div>
        <div class="lst-content">
          <div class="content-box">
            <div class="content-title">今日收入</div>
            <div class="content-info" style="color: #1D8704;">
              ￥{{ mem.dayIncome }}
            </div>
          </div>
          <div class="content-box">
            <div class="content-title">今日支出</div>
            <div class="content-info" style="color: #870101;">
              ￥{{ mem.dayExpense }}
            </div>
          </div>
          <div class="content-box">
            <div class="content-title">本月收入</div>
            <div class="content-info" style="color: #1D8704;">
              ￥{{ mem.mthIncome }}
            </div>
          </div>
          <div class="content-box">
            <div class="content-title">本月支出</div>
            <div class="content-info" style="color: #870101;">
              ￥{{ mem.mthExpense }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="add-Btn" @click="detailDialog = true">
      <svg class="icon" aria-hidden="true">
        <use xlink:href="#icon-bianji"></use>
      </svg>
    </div>
    <div class="bottom-tips">已经到底了 :)</div>
    <Dialog
      title="添加家庭成员"
      @close-dialog="detailDialog = false;" 
      :visible="detailDialog"
      :maskBtn="true"
      :width="300"
      :button-list="btnList"
    >
      <el-form
        ref="addFormRef"
        class="form-box"
        :rules="rules_add"
        :model="addForm"
        label-position="top"
        size="large"
      >
        <el-form-item label="成员用户名" prop="username">
          <el-input v-model="addForm.username" clearable />
        </el-form-item>
        <el-form-item label="成员密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password clearable />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
  import SubTitle from '@/components/SubTitle.vue';
  import message from '@/utils/message';
  import Dialog from '@/components/Dialog.vue';
  import { useUserStore } from '@/stores/user';
  import { getMembers, loginReq, addMembers, getUserInfo, getTodayInfo, getMonthInfo, delMembers } from '@/utils/api';
  import { reactive, ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';

  const useUser = useUserStore();
  const router = useRouter();
  let loadingMem = ref(true);

  let detailDialog = ref(false);
  const btnList = [
    {
      type: 'default',
      name: '取消',
      btnEvent: () => {
        detailDialog.value = false;
      },
      dis: false
    },
    {
      type: 'primary',
      name: '提交',
      btnEvent: () => {
        addFormRef.value.validate((valid) => {
          if(valid) {
            loginReq(addForm.username, addForm.password)
              .then(res => {
                if(res.data.msg === "成功") {
                  addMembers(useUser.userID, res.data.data.id)
                    .then(res => {
                      if(res.data) {
                        message.success('绑定成功');
                        getFamilyMems();
                      } else {
                        message.warning('绑定失败，请重试');
                      }
                      detailDialog.value = false;
                    })
                    .catch(err => {
                      message.warning('绑定失败，请重试');
                      console.warn(err);
                    });
                } else {
                  message.warning('认证失败，请重试');
                }
              })
              .catch(err => {
                message.warning('认证失败，请重试');
                console.warn(err);
              });
          }
        });
      },
      dis: false
    }
  ];
  let addFormRef = ref();
  let addForm = reactive({
    username: "",
    password: ""
  });

  let familyMembers = reactive([]);
  const getFamilyMems = () => {
    loadingMem.value = true;
    getMembers(useUser.userID)
      .then(res => {
        if(res.data.msg === "成功") {
          if(res.data.data) {
            res.data.data.forEach(mem => {
              getUserInfo(mem)
                .then(async res => {
                  if(res.data.msg === '成功') {
                    const dayBill = await getToday(res.data.data.id);
                    const mthBill = await getMonth(res.data.data.id);
                    familyMembers.push({
                      uid: res.data.data.id,
                      identity: "家人",
                      uname: res.data.data.name,
                      ...dayBill,
                      ...mthBill,
                    });
                  } else {
                    message.warning('获取成员信息失败');
                  }
                })
                .catch(err => {
                  message.warning('获取家庭成员失败');
                  console.warn(err);
                });
            });
            loadingMem.value = false;
          } else {
            loadingMem.value = false;
          }
        } else {
          message.warning('获取家庭成员失败');
        }
      })
      .catch(err => {
        message.warning('获取家庭成员失败');
        console.warn(err);
      });
  };
  const unTieRelation = (uid) => {
    message.confirm("确认解绑关系？", "操作", "warning", () => {
      delMembers(uid)
        .then(res => {
          if(res.data) {
            message.success('解绑成功');
            router.back();
          } else {
            message.warning('解绑失败，请重试');
          }
        })
        .catch(err => {
          console.warn(err);
          message.warning('解绑失败，请重试');
        });
    });
  };

  const getToday = async (id) => {
    try {
      const res = await getTodayInfo(id);
      if(res.data.msg === "成功") {
        return {
          dayIncome: res.data.data[0],
          dayExpense: res.data.data[1],
        }
      } else {
        message.warning('获取今日收支失败');
        console.warn(err);
        return {
          dayIncome: '--',
          dayExpense: '--',
        }
      }
    } catch {
      message.warning('获取今日收支失败');
      console.warn(err);
      return {
        dayIncome: '--',
        dayExpense: '--',
      }
    }
  }

  const getMonth = async (id) => {
    try {
      const res = await getMonthInfo(id);
      if(res.data.msg === "成功") {
        return {
          mthIncome: res.data.data[0],
          mthExpense: res.data.data[1],
        }
      } else {
        message.warning('获取当月收支失败');
        console.warn(err);
        return {
          mthIncome: '--',
          mthExpense: '--',
        }
      }
    } catch {
      message.warning('获取当月收支失败');
      console.warn(err);
      return {
        mthIncome: '--',
        mthExpense: '--',
      }
    }
  }

  const validateUname = (rule, value, callback) => {
    if(value === '')
      callback(new Error('用户名不能为空！'));
    else if(value.length < 5)
      callback(new Error('用户名需大于5位！'));
    else
      callback();
  };
  const validatePwd = (rule, value, callback) => {
    if(value === '')
      callback(new Error('密码不能为空！'));
    else if(value.length < 8)
      callback(new Error('密码需大于8位！'));
    else
      callback();
  };
  const rules_add = reactive({
    username: [{ validator: validateUname, trigger: 'blur' }],
    password: [{ validator: validatePwd, trigger: 'blur' }],
  });

  onMounted(() => {
    getFamilyMems();
  });
</script>

<style lang="scss" scoped>
  .family-list-container{
    width: 92%;
    min-height: 100px;
    margin: auto;
    .null-area{
      width: fit-content;
      padding: 0 8px 0 8px;
      margin: auto;
      margin-top: 20px;
      line-height: 50px;
      text-align: center;
      font-size: 14px;
      background-color: $theme-shadow00;
      border-radius: 8px;
      color: rgb(82, 82, 82);
      span{
        color: $theme-main;
        cursor: pointer;
      }
    }
    .family-list-item{
      width: 100%;
      height: 180px;
      margin-bottom: 20px;
      border-radius: 15px;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.04), 0 4px 8px 8px rgba(0, 0, 0, 0.04), 0 4px 8px 0 rgba(0, 0, 0, 0.08);
      overflow: hidden;
      .lst-header{
        width: 100%;
        height: 40px;
        background-color: $theme-shadow00;
        .lst-uname{
          float: left;
          line-height: 40px;
          width: fit-content;
          max-width: 120px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          margin-left: 15px;
          font-size: 16px;
          color: $theme-main-dark;
        }
        .lst-identy{
          float: left;
          height: 40px;
          width: 40px;
          margin-left: 10px;
          display: flex;
          align-items: center;
          span{
            width: 100%;
            line-height: 20px;
            text-align: center;
            font-size: 13px;
            border-radius: 6px;
            color: green;
            border: 1px solid green;
            background-color: rgba(227, 254, 227, 0.5);
          }
        }
        .lst-options{
          height: 40px;
          float: right;
          margin-right: 15px;
          display: flex;
          align-items: center;
        }
      }
      .lst-content{
        width: 100%;
        height: 140px;
        display: flex;
        flex-wrap: wrap;
        .content-box{
          width: 50%;
          height: 70px;
        }
        .content-title{
          width: 100%;
          line-height: 30px;
          font-size: 15px;
          color: $theme-shadow;
          text-align: center;
        }
        .content-info{
          width: 100%;
          line-height: 40px;
          font-size: 20px;
          text-align: center;
        }
      }
    }
  }
  .bottom-tips{
    width: fit-content;
    line-height: 30px;
    margin: auto;
    margin-top: 20px;
    font-size: 13px;
    color: $theme-shadow;
    user-select: none;
  }
  .add-Btn{
    width: 45px;
    line-height: 45px;
    color: white;
    text-align: center;
    background-color: $theme0;
    border-radius: 50%;
    position: fixed;
    right: 15px;
    bottom: 15px;
    font-size: 20px;
    box-shadow: 0 0 5px $theme-shadow;
    cursor: pointer;
  }
  .add-Btn:hover{
    background-color: $theme-main-light;
  }
</style>